package httputil

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"net/url"
	"strings"
)

/*
用与http请求的客户端
*/
func SendHttp[T any](url string, data any) (result *T, reserr error) {
	j, _ := json.Marshal(data)
	// fmt.Println(string(j))
	req, err := http.NewRequest("POST", url, bytes.NewReader(j))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	// for k, v := range header {
	// 	req.Header.Set(k, v)
	// }
	res, err := http.DefaultClient.Do(req)
	// res, err := http.Post(url, "application/json", strings.NewReader(string(j)))

	if err != nil {
		return nil, err
	}
	tmp, err := io.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		return nil, err
	}
	result = new(T)
	reserr = json.Unmarshal(tmp, result)
	return
}

/*
用与http请求的客户端
*/
func SendHttpByWWW[T any](url string, data url.Values) (result *T, reserr error) {
	res, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
	if err != nil {
		return nil, err
	}
	tmp, err := io.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		return nil, err
	}
	result = new(T)
	reserr = json.Unmarshal(tmp, result)
	return
}
